<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.tenantName" clearable class="filter-item" style="width: 150px;"
                placeholder="请输入租户姓名"/>

      <el-select v-model="listQuery.houseId" clearable style="width: 190px" class="filter-item" filterable
                 placeholder="请选择房屋">
        <el-option
          v-for="item in houseOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.roomId" clearable style="width: 190px" class="filter-item" filterable
                 placeholder="请选择房间">
        <el-option
          v-for="item in roomOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.tenantStauts" clearable style="width: 150px" class="filter-item" filterable
                 placeholder="请选择租户状态">
        <el-option
          v-for="item in tenantStautsOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.payrentStatus" clearable style="width: 150px" class="filter-item" filterable
                 placeholder="请选择交租状态">
        <el-option
          v-for="item in payrentStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-date-picker
        class="filter-item"
        value-format="yyyy-MM-dd"
        v-model="listQuery.payDate"
        type="date"
        placeholder="请选择交租时间">
      </el-date-picker>

      <el-button v-permission="['GET /admin/tenant/list']" class="filter-item" type="primary" style="background-color: #8B83D2;border-color: #8B83D2;" icon="el-icon-search"
                 @click="handleFilter">查找
      </el-button>
      <el-button v-permission="['POST /admin/tenant/create']" class="filter-item" type="primary"  style="background-color: #1AD227;border-color: #1AD227;" icon="el-icon-edit"
                 @click="handleCreate">添加
      </el-button>
      <el-button v-permission="['GET /admin/tenant/playFlagUpdate']" class="filter-item" type="primary"  style="background-color: #D26150;border-color: #D26150;" icon="el-icon-edit" @click="updataRenovate">立即刷新</el-button>


      <!--<el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" stripe border fit highlight-current-row
	style="width: 100%" row-style="height:35px" cell-style="padding:0">
      <el-table-column align="center" width="60" label="姓名" prop="tenantName"/>
      <el-table-column align="center" width="140" label="房间号" prop="roomId">
        <template slot-scope="scope">
          {{ formatRoomName(scope.row.roomId) }}
        </template>
      </el-table-column>
      <el-table-column align="center" width="80" label="房间价格" prop="roomId">
        <template slot-scope="scope">
          {{ formatRoomRent(scope.row.roomId) }}
        </template>
      </el-table-column>

      <el-table-column align="center" width="60" label="租金" prop="rent"/>

      <el-table-column align="center" width="70" label="租住时长" prop="monthNum"/>
      <el-table-column align="center" width="90" label="交租日期" prop="payDate"/>
      <el-table-column align="center" width="90" label="截止日期" prop="endDate"/>
      <el-table-column align="center" width="90" label="交租周期" prop="rentCycle">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.rentCycle === 1" size="small" type="success">押一付一</el-tag>
          <el-tag v-if="scope.row.rentCycle === 2" size="small" type="danger">押一付二</el-tag>
          <el-tag v-if="scope.row.rentCycle === 3" size="small" type="warning">押一付三</el-tag>
          <el-tag v-if="scope.row.rentCycle === 4" size="small" type="info">半年付</el-tag>
          <el-tag v-if="scope.row.rentCycle === 5" size="small" type="info">一把付</el-tag>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="备注" prop="remark"/>-->
      <el-table-column align="center" width="90" label="租户状态" prop="tenantStauts">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.tenantStauts === 0" size="small"  style="background-color: red">已退租</el-tag>
          <el-tag v-if="scope.row.tenantStauts === 1" size="small" type="success">在租</el-tag>
          <el-tag v-if="scope.row.tenantStauts === 2" size="small" type="warning">快到期</el-tag>
          <el-tag v-if="scope.row.tenantStauts === 3" size="small" type="info">其他</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" width="90" label="交租状态" prop="payrentStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.payrentStatus === 0" size="small" type="danger">未交</el-tag>
          <el-tag v-if="scope.row.payrentStatus === 1" size="small" type="success">已交</el-tag>
          <el-tag v-if="scope.row.payrentStatus === 2" size="small" type="warning">即将交租</el-tag>
          <el-tag v-if="scope.row.payrentStatus === 3" size="small" type="danger">欠租</el-tag>
          <el-tag v-if="scope.row.payrentStatus === 4" size="small" style="background-color: red">退租</el-tag>
          <el-tag v-if="scope.row.payrentStatus === 5" size="small" type="info">其他</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center"width="310" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.payrentStatus == 0" type="success" size="mini"
                     @click="handleRentIncome(scope.row)">收租
          </el-button>
          <el-button v-else-if="scope.row.payrentStatus == 2" type="success" size="mini"
                     @click="handleRentIncome(scope.row)">收租
          </el-button>
          <el-button v-else-if="scope.row.payrentStatus == 3" type="success" size="mini"
                     @click="handleRentIncome(scope.row)">收租
          </el-button>

          <el-button v-permission="['POST /admin/tenant/update']" type="primary" size="mini"
                     @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-permission="['POST /admin/tenant/delete']" type="danger" size="mini"
                     @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button v-permission="['POST /admin/tenant/delete']" type="primary" size="mini"
                     @click="wRoomcost(scope.row)">水电
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>
    <el-dialog  :visible.sync="wRoomcostVisible" width="50%">
       <el-form ref="costType"  :model="wRoomcostParams">
         <el-form-item label="收费类型" prop="costType">
        <el-select v-model="wRoomcostParams.costType" filterable placeholder="请选择">
          <el-option
            v-for="item in costTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
         </el-form-item>

         <el-form-item label="收费金额" prop="amount" >
           <el-input  style="width:200px;" v-model="wRoomcostParams.amount" />
         </el-form-item>

        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="wRoomcostVisible = false">取消</el-button>
        <el-button  type="primary" @click="wRoomcostInstall()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" label-width="120px">
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="所属房间" prop="roomId">
              <!--<el-input v-model="dataForm.roomId"/>-->
              <el-select v-model="dataForm.roomId" filterable placeholder="请选择">
                <el-option
                  v-for="item in roomOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="登录用户" prop="userId" style="display:none;">
              <el-input v-model="dataForm.userId"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="租户姓名" prop="tenantName">
              <el-input v-model="dataForm.tenantName"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="dataForm.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="租住人数" prop="tenantNumber">
              <el-input v-model="dataForm.tenantNumber"/>
            </el-form-item>
          </el-col>


          <el-col :span="11">
            <el-form-item label="租金" prop="rent">
              <el-input v-model="dataForm.rent"/>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="押金" prop="deposit">
              <el-input v-model="dataForm.deposit"/>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="水电押金" prop="lifeDeposit">
              <el-input v-model="dataForm.lifeDeposit"/>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="其他押金" prop="otherDeposit">
              <el-input v-model="dataForm.otherDeposit"/>
            </el-form-item>
          </el-col>



          <el-col :span="11">
            <el-form-item label="起租日期" prop="beginDate">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="dataForm.beginDate"
                type="date"
                placeholder="选择日期时间"
                align="right">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="dataForm.endDate"
                type="date"
                placeholder="选择日期时间"
                align="right">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="租住时长(月)" prop="monthNum">
              <el-input v-model="dataForm.monthNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="交租日期" prop="payDate">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="dataForm.payDate"
                type="date"
                placeholder="选择日期时间"
                align="right">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="交租周期" prop="rentCycle">
              <el-select v-model="dataForm.rentCycle" filterable placeholder="请选择">
                <el-option
                  v-for="item in rentCycleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="交租状态" prop="payrentStatus">
              <el-select v-model="dataForm.payrentStatus" filterable placeholder="请选择">
                <el-option
                  v-for="item in payrentStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="租户状态" prop="tenantStauts">
              <el-select v-model="dataForm.tenantStauts" filterable placeholder="请选择">
                <el-option
                  v-for="item in tenantStautsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="dataForm.sex" filterable placeholder="请选择">
                <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="dataForm.age"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
  import {createRoom } from '@/api/wRoomCostCollect'
  import {createTenant, listTenant, tenantIdOptions, updateTenant,renovate} from '@/api/tenant'
  import {createByTenantId} from '@/api/incomeRent'
  import {houseOptions} from '@/api/house'
  import {roomOptions,roomRentOptions} from '@/api/room'
  import {uploadPath} from '@/api/storage'
  import {getToken} from '@/utils/auth'
  import Pagination from '@/components/Pagination'
  import ElInput from "element-ui/packages/input/src/input";
  import ElInputNumber from "element-ui/packages/input-number/src/input-number"; // Secondary package based on el-pagination

  export default {
    name: 'Admin',
    components: {
      Pagination},
    data() {
      return {
        uploadPath,
        costParams:null,
        list: null,
        total: 0,
        roleOptions: null,
        houseOptions: null,
        listLoading: true,
        roomOptions: null,
        costTypeOptions: null,
        roomRentOptions: null,
        tenantIdOptions: null,
        wRoomcostParams: {
          tenantId: undefined,
          roomId: undefined,
          costType: undefined,
          amount: undefined,
          userId: this.$store.state.user.name
      },
        listQuery: {
          page: 1,
          limit: 20,
          tenantName: undefined,
          tenantStauts: undefined,
          payrentStatus: undefined,
          payDate: undefined,
          houseId: undefined,
          roomId: undefined
          // sort: 'add_time',
          // order: 'desc'
        },

        costTypeOptions: [{
        value: 0,
        label: '电费'
      }, {
        value: 1,
        label: '水费'
      }, {
        value: 2,
        label: '燃气费'
      }, {
          value: 3,
          label: '水电费'
        }, {
            value: 4,
            label: '其他'
          }],
        incomeTypeOptions: [{
          value: 0,
          label: '微信'
        }, {
          value: 1,
          label: '支付宝'
        }, {
          value: 2,
          label: '现金'
        }, {
          value: 3,
          label: '其他'
        }],
        sexOptions: [{
          value: '0',
          label: '男'
        }, {
          value: '1',
          label: '女'
        }],
        rentCycleOptions: [{
          value: 1,
          label: '押一付一'
        }, {
          value: 2,
          label: '押一付二'
        }, {
          value: 3,
          label: '押一付三'
        }, {
          value: 4,
          label: '半年付'
        }, {
          value: 5,
          label: '一把付'
        }],
        tenantStautsOptions: [{
          value: 0,
          label: '已退租'
        }, {
          value: 1,
          label: '在租'
        }, {
          value: 2,
          label: '快到期'
        }, {
          value: 3,
          label: '其他'
        }],
        payrentStatusOptions: [
          {
            value: 0,
            label: '未交租'
          },
          {
            value: 1,
            label: '已交租'
          }, {
            value: 2,
            label: '即将交租'
          }, {
            value: 3,
            label: '欠租'
          }, {
            value: 4,
            label: '退租'
          }, {
            value: 5,
            label: '其他'
          }],
        dataForm: {
          roomId: undefined,
          tenantStauts: undefined,
          tenantName: undefined,
          tenantNumber: undefined,
          age: undefined,
          sex: undefined,
          rent:undefined,
          deposit:undefined,
          lifeDeposit:undefined,
          otherDeposit:undefined,
          phone: undefined,
          payrentStatus: undefined,
          monthNum: undefined,
          beginDate: '',
          endDate: '',
          payDate: '',
          userId: this.$store.state.user.name,
          rentCycle: undefined
        },

        dialogFormVisible: false,
        wRoomcostVisible: false,
        rentDialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          roomId: [{required: true, message: '房间号不能为空', trigger: 'blur'}],
          tenantName: [{required: true, message: '租户姓名不能为空', trigger: 'blur'}],
          monthNum: [{required: true, message: '租住时长不能为空', trigger: 'blur'}],
          beginDate: [{required: true, message: '入住时间不能为空', trigger: 'blur'}],
          endDate: [{required: true, message: '结束时间不能为空', trigger: 'blur'}],
          payDate: [{required: true, message: '交租日期不能为空', trigger: 'blur'}],
          rentCycle: [{required: true, message: '交租周期不能为空', trigger: 'blur'}],
          tenantStauts: [{required: true, message: '租户状态不能为空', trigger: 'blur'}],
          rent: [{required: true, message: '租金不能为空', trigger: 'blur'}],
          deposit: [{required: true, message: '押金不能为空', trigger: 'blur'}]
        },
        downloadLoading: false
      }
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.getList()

      roomOptions()
        .then(response => {
          this.roomOptions = response.data.data.list
        })
      roomRentOptions()
        .then(response => {
          this.roomRentOptions = response.data.data.list
        })
      tenantIdOptions()
        .then(response => {
          this.tenantIdOptions = response.data.data.list
        })
      houseOptions()
        .then(response => {
          this.houseOptions = response.data.data.list
        })
    },
    methods: {
/*      updataRenovate(){
        renovate()
        this.handleFilter()
      },*/
      formatRoomName(roomId) {
        for (let i = 0; i < this.roomOptions.length; i++) {
          if (roomId === this.roomOptions[i].value) {
            return this.roomOptions[i].label
          }
        }
      },
      formatRoomRent(roomId) {
        for (let i = 0; i < this.roomRentOptions.length; i++) {
          if (roomId === this.roomRentOptions[i].value) {
            return this.roomRentOptions[i].label
          }
        }
      },

      getList() {
        this.listLoading = true
        listTenant(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      updataRenovate() {
        this.listLoading = true
        renovate(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          roomId: undefined,
          tenantStauts: undefined,
          tenantName: undefined,
          tenantNumber: undefined,
          age: undefined,
          sex: undefined,
          phone: undefined,
          rent:undefined,
          deposit:undefined,
          lifeDeposit:undefined,
          otherDeposit:undefined,
          payrentStatus: undefined,
          monthNum: undefined,
          beginDate: '',
          endDate: '',
          payDate: '',
          userId: this.$store.state.user.name,
          rentCycle: undefined
        }
      },
      uploadAvatar: function (response) {
        this.dataForm.avatar = response.data.url
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createTenant(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      wRoomcost(row){
        this.wRoomcostVisible=true
        this.wRoomcostParams.tenantId = row.id
        this.wRoomcostParams.roomId = row.roomId
      },
      handleRentIncome(row) {
        // var values = this.formatRoomRent(row.roomId)
        var values = row.rent
        if(row.rentCycle===2){
          values=values*2
        }
        if(row.rentCycle===3){
          values=values*3
        }
        if(row.rentCycle===4){
          values=values*6
        }
        this.$prompt('该用户还未交租，是否确认已收租？', '确认信息', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          inputValue: values,
          dangerouslyUseHTMLString: true,
          showInput:true
        }).then(({ value }) => {
          var params = {"tenantId": row.id,"incomeAmount":value, "userId": this.$store.state.user.name}
          createByTenantId(params)
            .then(() => {
              this.$notify.success({
                title: '成功',
                message: '交付金额: ' + value
              })
              this.listQuery.page = 1
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        });
      },
      wRoomcostInstall() {
       var value =this.wRoomcostParams.amount
        this.$alert('确认水电燃气费？', '确认信息', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
        }).then(({ value }) => {
          createRoom(this.wRoomcostParams)
            .then(() => {
              this.$notify.success({
                title: '成功',
                message: '交付金额: ' + value
              })
              this.listQuery.page = 1
              this.getList()
              this.wRoomcostVisible = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
          this.wRoomcostVisible = false
        });
      },

      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateTenant(this.dataForm)
              .then(() => {
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },

      handleDelete(row) {
        this.$confirm('是否确认已删除？', '确认信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          row.delFlag = 1
          updateTenant(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        });
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['房间ID', '房间名称', '房间头像']
          const filterVal = ['id', 'username', 'avatar']
          excel.export_json_to_excel2(
            tHeader,
            this.list,
            filterVal,
            '房间信息'
          )
          this.downloadLoading = false
        })
      }
    }
  }
</script>
